from django.shortcuts import render, redirect
from app01 import models

# Create your views here.


def depart_list(request):

    queryset = models.Deparment.objects.all()

    return render(request, "depart_list.html", {"queryset": queryset})


def depart_add(request):
    if request.method == "GET":
        return render(request, "depart_add.html")

    # 获取POAST提交数据
    title = request.POST.get("title")
    # 保存到数据库
    models.Deparment.objects.create(title=title)
    # 重定向回部门列表
    return redirect("/depart/list/")


def depart_delete(request):

    # 获取ID
    nid = request.GET.get('nid')
    # 删除
    models.Deparment.objects.filter(id=nid).delete()
    # 重定向到部门列表
    return redirect("/depart/list/")


def depart_edit(request, nid):
    if request.method == "GET":
        # 根据nid获取数据
        row_object = models.Deparment.objects.filter(id=nid).first()

        return render(request, "depart_edit.html", {"row_object": row_object})

    title = request.POST.get("title")
    models.Deparment.objects.filter(id=nid).update(title=title)
    # 重定向到部门列表
    return redirect("/depart/list/")




